import { goodslist, goodscount } from '../../api/api'
const state = {
  goodListData: [],
  // 页面显示条数
  pageSize: 3,
  // 页码
  pageNum: 1,
  // 总条数
  count: 0
}

// 类似于计算属性 对state力度数据进行处理返回
const getters = {
  // 函数形式
  getGoods (state) {
    return state.goodListData
  },
  getSize (state) {
    return state.pageSize
  },
  getCount (state) {
    return state.count
  }
}
const mutations = {
  REQ_GOODSLIST (state, payload) {
    state.goodListData = payload
  },
  REQ_GOODSCOUNT (state, payload) {
    state.count = payload
  },
  REQ_PAGENUM (state, payload) {
    state.pageNum = payload
  }
}
const actions = {
// 如果想修改state的数据 通过调用mutations里的commit方法
// 获取列表
  getGoodslist (context) {
    goodslist({ size: context.state.pageSize, page: context.state.pageNum }).then(res => {
      const list = res.list ? res.list : []
      if (context.state.pageNum !== 1 && list.length === 0) {
        // 重新计算页码
        context.dispatch('changePageAction', context.state.pageNum - 1)
      }

      context.commit('REQ_GOODSLIST', res.list)
    })
  },
  // 获取总条数
  getGoodscount (context) {
    //
    goodscount().then(res => {
      console.log(res)
      if (res.code === 200) {
        context.commit('REQ_GOODSCOUNT', res.list[0].total)
      }
    })
  },
  // 获取当前页重新调用列表
  changePageAction (context, n) {
    // 赋值新的页码
    context.commit('REQ_PAGENUM', n)
    // 重新调用
    context.dispatch('getGoodslist')
  }

}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
